package com.ruoyi.blog.service.impl;

import com.ruoyi.blog.dao.AuthUserDao;
import com.ruoyi.blog.pojo.AuthUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AuthUserDao authUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<AuthUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", username);
        AuthUser authUser = authUserDao.selectOne(queryWrapper);
        if (authUser == null) {
            throw new UsernameNotFoundException("该账号不存在！");
        }
        if (authUser.getStatus().equals("n")) {
            throw new UsernameNotFoundException("该账号已封禁！");
        }
        // 设置权限
        // List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
        // 从数据库查询返回user对象，得到用户名密码
        return new User(authUser.getUsername(), authUser.getPassword(), new ArrayList<>());
    }
}
